package dataStructure.others;

import java.util.HashMap;

/**
 * Description 针对各种字符串的字典树，路径不仅仅是a~z对应的26个，用HashMap<Integer, Node2>表示ascii码值对应的node。
 *
 * @ClassName dataStructure.others.TrieTree2
 * @Version 1.0
 * @Date: 2022/2/18 16:53
 * @Author xuyi
 */
public class TrieTree2 {
    public class Node2 {
        public int pass;
        public int end;
        public HashMap<Integer, Node2> next;

        public Node2() {
            pass = 0;
            end = 0;
            next = new HashMap<>();
        }
    }

    public class Trie2 {
        public Node2 root;

        public Trie2() {
            root = new Node2();
        }

        public void insert(String word) {
            if (word == null || word.equals("")) {
                return;
            }
            Node2 node = root;
            node.pass++;
            char[] chars = word.toCharArray();
            int idx;
            for (int i = 0; i < chars.length; i++) {
                idx = chars[i];
                if (!node.next.containsKey(idx)) {
                    node.next.put(idx, new Node2());
                }
                node = node.next.get(idx);
                node.pass++;
            }
            node.end++;
        }

        public void delete(String word) {
            if (search(word) == 0) {
                return;
            }
            Node2 node = root;
            node.pass--;
            char[] chars = word.toCharArray();
            int idx;
            for (int i = 0; i < chars.length; i++) {
                idx = chars[i];
                if (--node.next.get(idx).pass == 0) {
                    node.next.remove(idx);
                    return;
                }
                node = node.next.get(idx);
            }
            node.end--;
        }

        /**
         * 查找指定字符串在前缀树中出现的次数
         */
        public int search(String word) {
            if (word == null || word.equals("")) {
                return 0;
            }
            Node2 node = root;
            char[] chars = word.toCharArray();
            int idx;
            for (int i = 0; i < chars.length; i++) {
                idx = chars[i];
                if (!node.next.containsKey(idx)) {
                    return 0;
                }
                node = node.next.get(idx);
            }
            return node.end;
        }
    }
}